package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author MJJ
 * @date 2025-06-09
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);


    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }


    /**
     * 过滤报警
     */
    @Override
    public void alertFilter() {

        //查询所有规则，遍历规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count < 0){
            return;
        }
        //查询所有上报数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (Collections.isEmpty(values)){
            return;
        }
        //解析上报的数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value -> {
            deviceDataList.addAll(JSONUtil.toList(value.toString(), DeviceData.class));
        });

        //获取报警规则，进行验证
        deviceDataList.forEach(deviceData -> { alertFilter(deviceData);});
    }

    private void alertFilter(DeviceData deviceData) {
        //判断当前数据是否超过1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60){
            log.info("数据超过1分钟");
            return;
        }

        //查询所有产品的规则及物模型规则
        //查询所有该产品的规则
        List<AlertRule> allRuleList = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, "-1"));

        //查询该产品的物模型规则
        List<AlertRule> iotRulelist = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1));

        //合并两个规则
        Collection<AlertRule> alertRules = CollUtil.addAll(allRuleList, iotRulelist);
        //如果为空，则返回
        if (CollUtil.isEmpty(alertRules)){
            return;
        }
        //按照过滤规则和每一条数据进行匹配
        alertRules.forEach(alertRule -> { deviceDataAlarmHandle(alertRule, deviceData);});
    }
    @Autowired
    private DeviceMapper  deviceMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 过滤数据是否触发报警规则
     *
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandle(AlertRule alertRule, DeviceData deviceData) {

        //判断上报时间是否在规则的生效时间内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //获取上报时间
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        //如果不在上报时间内则结束请求
        if (!alarmTime.isAfter(startTime) || !alarmTime.isBefore(endTime)){
            return;
        }

        //获取IotID
        String iotId = alertRule.getIotId();
        //统计报警次数的key
        String countKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX  + iotId + ":" + alertRule.getFunctionId() + ":" +alertRule.getId();


        //将上报的数据与规则中的阈值进行对比
        //左边参数：上报的数据，右边参数：规则中的阈值 左>右 ,左=右 返回0，左<右，返回-1
        int compare = NumberUtil.compare(Double.valueOf(deviceData.getDataValue()),alertRule.getValue());
        if ((alertRule.getOperator().equals(">=") && compare >= 0) || (alertRule.getOperator().equals("<") && compare < 0)) {
            //超过阈值
            log.info("超过阈值");
        }else {
            //未超过阈值
            redisTemplate.delete(countKey);
        }
        //异常数据到达这里需要判断是否在沉默期
       String silentKey =  CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + alertRule.getFunctionId() + ":" +alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if (ObjectUtil.isNotEmpty(silentData)){
            log.info("在沉默期");
            return;
        }
        String countData = redisTemplate.opsForValue().get(countKey);
        int count = StringUtils.isEmpty(countData) ? 1 : Integer.parseInt(countData) + 1;
        //如果count等于持续周期，则触发报警
        if (ObjectUtil.notEqual(count, alertRule.getDuration())){
            //不相等
            redisTemplate.opsForValue().set(countKey,count+"");
            return;
        }
        //删除redis  中的报警数据
        redisTemplate.delete(countKey);
        //存储数据，设置一个过期时间，是规则中的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);


        //有报警数据，就通过它找到对应的人
        List<Long> userIds = new ArrayList<>();
        if (alertRule.getAlertDataType().equals(0)){
            //这是老人的异常数据
            if (deviceData.getLocationType().equals(0)){
                //说明是随身设备，可以通过设备id查到老人id,再用老人id去找对应护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);

            }else {
                //说明是床位设备，可以通过老人id查到设备id，再用设备id去找对应护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            //说明是设备异常数据
            userIds = userRoleMapper.selectUserIdByRoleName("维修工");
        }

        //不管是那种情况都要通知超级 管理员
        List<Long> managerIds  = userRoleMapper.selectUserIdByRoleName("超级管理员");
        //合并管理员和护理员
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);
        //保存报警数据
        insertAlertRule(alertRule,deviceData,allUserIds);
    }

    @Autowired
    private IAlertDataService alertDataService;
    /**
     * 保存报警数据
     * @param alertRule
     * @param deviceData
     * @param allUserIds
     */
    private void insertAlertRule(AlertRule alertRule, DeviceData deviceData, Collection<Long> allUserIds) {

        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        //设置报警原因
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionId(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        //遍历userIds
        List<AlertData> collect = allUserIds.stream().map(userId -> {
            AlertData dbalertData = BeanUtil.toBean(alertData, AlertData.class);
            dbalertData.setId(null);
            return dbalertData;
        }).collect(Collectors.toList());
        //批量保存
        alertDataService.saveBatch(collect);
    }
}
